package cicd_projects

import (
	"context"
	"errors"
	"fmt"
	"github.com/wonderivan/logger"
	"k8s-platform/dao"
	"k8s-platform/db"
	"k8s-platform/model"
	service "k8s-platform/service/jenkins"
	"strings"
)

var Cicdprojects cicdprojects

type cicdprojects struct{}

// 新增
func Create_apps(data model.InputData) error {
	if err := dao.Create_apps(data); err != nil {
		return err
	}
	return nil
}

// 列表
func (*cicdprojects) List() ([]*model.Cicd_projects, error) {
	return dao.Cicdprojects.List()
}

// 运行
func Run_apps(data model.InputData) error {
	ctx := context.Background()
	for _, app := range data.AddAppList {
		parts := strings.Split(app.Name, "/")
		_, err := service.Jenkins_init.JenkinsClient.BuildJob(ctx, parts[1], nil)
		if err != nil {
			logger.Error(parts[1]+"执行流水线未找到", err)
			return errors.New(parts[1] + "执行流水线未找到" + err.Error())
		}
	}
	return nil
}

func Delete_apps(puldata model.InputData) (string, error) {
	delete_data := &model.Cicd_projects{Regionaname: puldata.Regionaname}

	//更具名称查询ID
	var id int64
	db.DB.Model(&model.Cicd_projects{}).Where("regionaname = ?", puldata.Regionaname).Pluck("id", &id)

	// 删除关联的 AppItem 记录
	err := db.DB.Where("cicd_project_id = ?", id).Delete(&model.AppItem{}).Error
	if err != nil {
		return "删除关联项失败", fmt.Errorf("删除关联项失败: %w", err)
	}

	// 删除 Cicd_projects 记录
	tx := db.DB.Where("regionaname = ?", delete_data.Regionaname).Delete(delete_data).Error
	if tx != nil {
		return "删除项目失败", fmt.Errorf("删除项目失败: %w", tx)
	}

	fmt.Println("删除成功")
	return "删除成功", nil
}
